﻿using System.Collections.Generic;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class HyperlinkString
    {
        private string _data;
        public static explicit operator string(HyperlinkString hs)
    {
        if (hs == null)
            return null;
            return hs._data;
    }
        public static explicit operator HyperlinkString(string value)
        {
            if (value == null)
                return null;
            return new HyperlinkString {_data = value};
        }
        public void Read(BinaryReader reader)
        {
            uint length = reader.ReadUInt32();
            List<char> chars = new List<char>();
            for (int i = 0; i < length; i++)
            {
                char c = (char) reader.ReadUInt16();
                if (c != '\0')
                    chars.Add(c);
            }
            this._data = new string(chars.ToArray());

        }

        public void Write(BinaryWriter writer)
        {
            uint length = (uint) (this._data.Length + 1);
            writer.Write(length);
            foreach (char c in _data)
                writer.Write((ushort)c);
            writer.Write((ushort)'\0');

        }
    }
}